import React, {
    useEffect,
    useState,
    useCallback,
    useMemo
} from "react";
import md5 from 'md5'
import { message, Select, Checkbox, Switch, Spin } from "antd";
import Modal from "../../../common/component/modal";
import { useDispatch, useSelector } from "react-redux";
import axiosMethod from "../../../util/axios";
import CONFIG from "../../../util/config";
import Search from "../../../common/component/search";
import Empty from "../../../common/component/empty";
import { getQueryVariable } from "../../../util";
import Scrollbars from "react-custom-scrollbars";
import { LgPaginationA } from "lancoo-web-ui";
import useGetThem from "../../../hooks/useGetThem";
import "./index.scss";

const {
    appAddr
} = CONFIG;
const { Option } = Select;


function Todo(props) {
    let {
        userInfo,
        currentIdentity,
        isEdu,
        officeUrl
    } = useSelector(state => state);


    const dispatch = useDispatch();
    const [messageApi, contextHolder] = message.useMessage();
    const [loadVisible, setLoadVisible] = useState(false);
    const [settingVisible, setSettingVisible] = useState(false);
    const [settingInfo, setSettingInfo] = useState([]);
    const [typeList, setTypeList] = useState([]);
    const [currentState, setCurrentState] = useState('')
    const [currentType, setCurrentType] = useState("");
    const [keyword, setKeyword] = useState("");

    const [listTotal, setListTotal] = useState(0)

    const [messageInfo, setMessageInfo] = useState({});
    const [currentIndex, setCurrentIndex] = useState(1);
    const [selectList, setSelectList] = useState([]);

    //#region
    //打开exe客户端
    //initFunc为初始化后的回调函数，成功返回操作对象;失败返回false，表明基础插件不存在
    //操作对象可以调用start(proName, moduleName, url, exeName, exeParam)方法，启动exe
    //操作对象在谷歌火狐及ie10以上浏览器可调用sendmessage(proName, moduleName, msgData)方法，向指定模块发送消息；
    //也可在谷歌火狐及ie10以上浏览器实现reciveExeMessageFunc(msg)函数接收消息
    //当websocket被断开时，将触发reConnectFunc回调函数，此时，可重新建立对象并连接
    // function BsToCsFuncAssistantInfoCenter(initFunc, reciveExeMessageFunc, reConnectFunc) {
    //     this.checkBase = false;
    //     this._Socket = null;
    //     this.objState = 0;
    //     this.objConnect = false;
    //     this.socketArrayLength = 5;
    //     this.activexObj = null;

    //     var maxPort = 15326;
    //     var browser = getBrowserInfo();

    //     if (browser != null && browser[0] == "firefox") {
    //         //this.socketArrayLength = 2;
    //         //maxPort = 15323;
    //     }

    //     var socketArray = new Array();
    //     var thisObj = this;

    //     for (var i = 15321; i < maxPort; ++i) {
    //         try {
    //             var tmpSocket = new WebSocket("ws://127.0.0.1:" + i);
    //             //tmpSocket.CONNECTING
    //             socketArray.push(tmpSocket);

    //             tmpSocket.onclose = function () {
    //                 if (!thisObj.checkBase) {
    //                     --thisObj.socketArrayLength;

    //                     if (thisObj.socketArrayLength <= 0) {
    //                         if (typeof initFunc == 'function') {
    //                             initFunc(false);
    //                         }
    //                     }
    //                 }

    //                 else {

    //                     //说明本来连接到了socket服务器，但是突然断开了，最有可能是因为服务被停止了，以及卸载或重装了基础插件
    //                     if (typeof reConnectFunc == 'function') {
    //                         reConnectFunc();
    //                     }
    //                 }
    //             }

    //                 ;

    //             tmpSocket.onopen = function () {
    //                 switch (this.readyState) {
    //                     case 0:
    //                     case 2: case 3: break;
    //                     case 1:
    //                         thisObj.objState = 0;
    //                         thisObj.objConnect = true;
    //                         thisObj._Socket = this;
    //                         thisObj.checkBase = true;

    //                         if (typeof initFunc == 'function') {
    //                             initFunc(thisObj);
    //                         }

    //                         if (typeof reciveExeMessageFunc == 'function') {
    //                             this.onmessage = function (e) {
    //                                 reciveExeMessageFunc(e.data);
    //                             }
    //                         }

    //                         break;
    //                 }
    //             }
    //         }

    //         catch (e) {
    //             try {
    //                 thisObj.objState = 1;
    //                 thisObj.objConnect = true;
    //                 createActivexObj("B94EBF17-D4AB-4A91-A298-008DDA8AEFB3", "LgClientStart", "", 1, 1);
    //                 thisObj.activexObj = document.getElementById("LgClientStart");

    //                 if (thisObj.activexObj.CheckOcx() == "ok") {
    //                     thisObj.objConnect = true;
    //                     thisObj.checkBase = true;

    //                     if (typeof initFunc == 'function') {
    //                         initFunc(thisObj);
    //                     }
    //                 }

    //                 else {
    //                     if (typeof initFunc == 'function') {
    //                         initFunc(false);
    //                     }
    //                 }
    //             }

    //             catch (e) {
    //                 if (typeof initFunc == 'function') {
    //                     initFunc(false);
    //                 }
    //             }

    //             break;
    //         }
    //     }

    // }

    // BsToCsFuncAssistantInfoCenter.prototype.start = function (proName, moduleName, url, exeName, exeParam) {
    //     if (this.objState == 0) {
    //         if (this.objConnect) {
    //             var char1 = String.fromCharCode(1);
    //             var char2 = String.fromCharCode(2);
    //             //连接成功后
    //             this._Socket.send(proName + char1 + moduleName + char1 + "001" + char2 + url + char2 + exeName + char2 + exeParam);
    //             return true;
    //         }

    //         else {
    //             return false;
    //         }
    //     }

    //     else {
    //         if (this.objConnect) {
    //             this.activexObj.NotifyService("5$" + url + "," + proName + "," + moduleName + "," + exeName + "#" + exeParam);
    //             return true;
    //         }

    //         else {
    //             return false;
    //         }
    //     }
    // }

    // //如果页面需要接收exe发送的消息，则需要在initFunc函数内调用此函数
    // BsToCsFuncAssistantInfoCenter.prototype.willReciveMessage = function (proName, moduleName) {
    //     if (this.objState == 0) {
    //         if (this.objConnect) {
    //             var char1 = String.fromCharCode(1);
    //             var char2 = String.fromCharCode(2);
    //             this._Socket.send(proName + char1 + moduleName);
    //             return true;
    //         }
    //     }

    //     return false;
    // }

    // BsToCsFuncAssistantInfoCenter.prototype.sendMessage = function (proName, moduleName, msgData) {
    //     if (this.objState == 0) {
    //         if (this.objConnect) {
    //             var char1 = String.fromCharCode(1);
    //             var char2 = String.fromCharCode(2);
    //             //给exe发信息
    //             this._Socket.send(proName + char1 + moduleName + char1 + "000" + char2 + msgData);
    //             return true;
    //         }
    //     }

    //     return false;
    // }

    // //如果页面需要获取本机mac地址，则需要在initFunc函数内调用此函数，将在reciveExeMessageFunc内接收到{LocalMacIDs:[mac1,mac2,...,macN]}的json字符串
    // BsToCsFuncAssistantInfoCenter.prototype.GetMacIDs = function (proName, moduleName) {
    //     if (this.objState == 0) {
    //         if (this.objConnect) {
    //             var char1 = String.fromCharCode(1);
    //             var char2 = String.fromCharCode(2);
    //             //给服务发信息
    //             this._Socket.send(proName + char1 + moduleName + char1 + "002" + char2 + "");
    //             return true;
    //         }
    //     }

    //     return false;
    // }

    // //检测浏览器类型及版本
    // function getBrowserInfo() {
    //     var Sys = {}

    //         ;
    //     var ua = navigator.userAgent.toLowerCase();
    //     var s;
    //     var res = new Array();
    //     // (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] : (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] : (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] : (s = ua.match(/opera\/([\d.]+)/)) ? Sys.opera = s[1] : (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;

    //     if (Sys.ie) {
    //         res[0] = "ie";
    //         res[1] = Sys.ie;
    //     }

    //     else if (! !window.ActiveXObject || "ActiveXObject" in window) {
    //         res[0] = "ie";
    //         res[1] = "11.0";
    //     }

    //     else if (Sys.firefox) {
    //         res[0] = "firefox";
    //         res[1] = Sys.firefox;
    //     }

    //     else if (Sys.chrome) {
    //         res[0] = "chrome";
    //         res[1] = Sys.chrome;
    //     }

    //     else if (Sys.safari) {
    //         res[0] = "safari";
    //         res[1] = Sys.safari;
    //     }

    //     else if (Sys.opera) {
    //         res[0] = "opera";
    //         res[1] = Sys.opera;
    //     }

    //     else {
    //         res = null;
    //     }

    //     return res;
    // }

    // //---------------------浏览器兼容Begin-----------------------------//
    // //创建ActiveX控件实例
    // function createActivexObj(clsid, objID, evtArr, width, height) {
    //     if (document.getElementById(objID) == null) {
    //         var browserInfo = getBrowserInfo();
    //         var AcXobj;

    //         if (browserInfo[0] == "ie") {
    //             AcXobj = document.createElement("OBJECT");
    //             AcXobj.setAttribute("classid", "clsid:{" + clsid + "}");

    //             if (evtArr) {
    //                 for (var i = 0; i < evtArr.length; i++) {
    //                     var evts = evtArr[i].split(":");
    //                     document.body.innerHTML += ('<script for="' + objID + '" event="' + evts[0] + '(' + setArgs(evts[2]) + ')">' + evts[1] + '(' + setArgs(evts[2]) + ');</script>');
    //                 }
    //             }
    //         }

    //         AcXobj.setAttribute("id", objID);

    //         if (width == null || height == null || width == 0 || height == 0) {
    //             AcXobj.setAttribute("height", 0);
    //             AcXobj.setAttribute("width", 0);

    //             if (browserInfo[0] == "ie" && (browserInfo[1] == "6.0" || browserInfo[1] == "7.0")) {
    //                 AcXobj.style.display = "none";
    //             }
    //         }

    //         else {
    //             AcXobj.setAttribute("height", height);
    //             AcXobj.setAttribute("width", width);
    //         }

    //         document.body.appendChild(AcXobj);
    //     }

    //     function setArgs(alenght) {
    //         if (alenght == null) return "";
    //         var res = "";

    //         for (var ai = 0; ai < alenght; ai++) {
    //             res += "acxArg_" + ai + ",";
    //         }

    //         res = res.substr(0, res.length - 1);
    //         return res;
    //     }
    // }

    // //---------------------浏览器兼容End-----------------------------//
    // function getStartPorotol(AccessParam, it, type) {
    //     // if(type === "out"){
    //     //   this.state.Bs2Cs.start(AccessParam.proName, AccessParam.moduleName, AccessParam.BasicWebUrl, AccessParam.exeName, AccessParam.exeParam);
    //     //   return;
    //     // }
    //     var lg_ic = getQueryVariable('lg_ic')

    //     var lg_tk = sessionStorage.getItem('token');
    //     var BasicWebRootUrl = window._BasicProxy
    //     var UserID = userInfo.UserID
    //     var UserName = userInfo.UserName
    //     var SchoolID = userInfo.SchoolID
    //     AccessParam = AccessParam.replace(/{token}/, lg_tk);
    //     AccessParam = AccessParam.replace(/{lg_ic}/, lg_ic);
    //     AccessParam = AccessParam.replace(/{identitycode}/, lg_ic);
    //     AccessParam = AccessParam.replace(/{userid}/, UserID);
    //     AccessParam = AccessParam.replace(/{username}/, UserName);
    //     AccessParam = AccessParam.replace(/{MainServerAddr}/, BasicWebRootUrl);
    //     AccessParam = AccessParam.replace(/{ServerAddr}/, it.WebSvrAddr);
    //     AccessParam = AccessParam.replace(/{schoolid}/, SchoolID);

    //     // SaveEntranceAccessBehaviorRecordFn(item)
    //     if (AccessParam.slice(0, 9) !== 'lgsoft://') {
    //         window.open(AccessParam, "_blank");
    //         return
    //     }


    //     AccessParam = AccessParam.replace(/{MainServerAddrNoHttp}/, BasicWebRootUrl.slice(7, BasicWebRootUrl.length - 1));
    //     if (_clientObj) {

    //         const proName = AccessParam.split('::')[0].split('://')[1];

    //         const moduleName = AccessParam.split('::')[1];

    //         const exeName = AccessParam.split('::')[2];


    //         const BasicWebUrl = sessionStorage.getItem("PsnMgrMainServerAddr");

    //         // MainServerAddrNoHttp
    //         const token = sessionStorage.getItem('PsnMgrToken');
    //         var porotol = AccessParam.split('::')[3].replace(/{MainServerAddr}/g, BasicWebUrl).replace(/{token}/g, token);

    //         if (porotol.indexOf("Convert.ToBase64String(") > -1) {

    //             porotol = "://" + window.btoa(encodeURIComponent(porotol.slice(23, -1)));

    //         }

    //         console.log(proName, moduleName, BasicWebUrl, exeName, porotol);
    //         _clientObj.start(proName, moduleName, BasicWebUrl, exeName, porotol);

    //     }

    // }

    // var _clientObj = new BsToCsFuncAssistantInfoCenter(InitFunc);
    // var _clientFlag = true;

    // function InitFunc(param) {
    //     if (!param) {
    //         _clientFlag = false;
    //     }
    // }

    // function commonOpenClient(porotol, it) {
    //     console.log(porotol, it)
    //     if (!_clientFlag) {
    //         alert('您还未安装基础插件包，请先下载和安装插件包！')
    //     } else {
    //         setTimeout(function () {
    //             getStartPorotol(porotol, it)
    //         }, 100);
    //     }
    // }

    const selectStatus = useMemo(() => {
        let sign = 0;
        if (selectList.length > 0 && selectList.length < 9) {
            if (selectList.length == messageInfo.length) {
                sign = 2;
            } else {
                sign = 1;
            }
        } else if (selectList.length === 9) {
            sign = 2;
        }
        // console.log(sign, selectList)
        return sign;
    }, [selectList]);

    const settingChange = useCallback((value) => {   //控制消息设置弹窗显隐
        setSettingVisible(value);
    }, []);
    const getSettingInfo = useCallback(() => {  //获取消息设置信息
        axiosMethod({
            type: "get",
            url: "/api/setting/list/getPageList",
            body: {
                schoolId: userInfo.SchoolID,
                userId: userInfo.UserID,
                userType: userInfo.UserType,
                schoolLevel: userInfo.SchoolLevel,
                environment: isEdu ? 1 : 2
            },
            callback: function (res) {
                let info = JSON.parse(JSON.stringify(res.msgTypeList));
                Array.isArray(info) &&
                    info.forEach((item) => {
                        let sign = false;
                        selectList.forEach((child, index) => {
                            if (item.templateId === child.templateId) {
                                sign = true;
                            }
                        })
                        let flag = item.templateList.some(child => {
                            return child.isPush == 0
                        })
                        item.check = flag;
                    });
                setSettingInfo(info);
                settingChange(true);
            }
        });
    }, [settingChange, userInfo]);

    const changeType = useCallback((data) => {
        setCurrentType(data.key);
    }, []);
    const getList = useCallback((pageIndex = currentIndex) => {   //获取消息列表
        setLoadVisible(true);
        if (keyword) {
            pageIndex = 1
        }
        axiosMethod({
            type: "get",
            url: "/api/system/list/getPageList",
            body: {
                pageIndex: 1,
                pageSize: 9999,
                status: currentState,
                userType: userInfo.UserType,
                userId: userInfo.UserID,
                keyWord: keyword,
                schoolId: userInfo.SchoolID
            },
            isBackAll: true,
            callback: function (res) {
                Array.isArray(res.data) && res.data.forEach(item => {
                    item.check = false
                })
                let realCount = 0, realTodoList = [], dealTodoList = [];
                let noticeList = res.data
                noticeList.map(function (item, idx) {
                    if (item.receiverType == 0 || item.receiverType == 1 || item.receiverType == 4 || item.receiverType == 5) {
                        realCount++;
                        realTodoList.push(item)
                    }
                })

                if (pageIndex > 1 && realTodoList.length > 0) {
                    dealTodoList = realTodoList.slice((pageIndex - 1) * 9, pageIndex * 9)
                } else {
                    dealTodoList = realTodoList.slice(0, 9)
                }

                setMessageInfo(dealTodoList);
                setListTotal(Number(realCount))
                setLoadVisible(false);
            }
        });
    }, [currentIndex, userInfo, currentState, keyword]);

    const searchMethod = useCallback((value) => {  //搜索函数
        setKeyword(value);
        // if (currentIndex === 1) {
        //     getList();
        // } else {
        //     setCurrentIndex(1);
        // }
    }, []);

    // 处理日程消息查看 
    const handleScheduleMsg=(data)=>{
        if (officeUrl) {
            let sendObj = {
                userId: userInfo.UserID,
                userType: userInfo.UserType,
                schoolId: userInfo.SchoolID,
                scheduleId: data.msgId
            }
            if (isEdu) {
                sendObj = {
                    userId: userInfo.UserID,
                    userType: userInfo.UserType,
                    eduId: userInfo.SchoolID,
                    scheduleId: data.msgId
                }
            }
            axiosMethod({
                type:'get',
                url:officeUrl+"/api/schedule/info/detail",
                body:sendObj,
                callback:function(res){
                    const {scheduleId}=res
                    let jumpUrl = officeUrl + 'html/index/index.html?lg_tk=' + sessionStorage.getItem("token") + '&scheduleId=' + scheduleId
                    if (isEdu) {
                        jumpUrl = officeUrl + 'homepage/web/index.html?lg_tk=' + sessionStorage.getItem("token") + '&scheduleId=' + scheduleId
                    }
                    window.open(jumpUrl)
                }
            })
        }
    }

    const noticeClick = useCallback((data) => {
        if (!data.pcLink) {
            if (data.templateId === '20003' || data.templateId === '20001') {
                handleScheduleMsg(data)
            }
            return
        }
        if (data.pcLinkType == 1) {
            window.getWebAddr(data.sysId, function (webAddr) {
                let url = data.pcLink
                    .replace("[token]", sessionStorage.getItem("token"))
                    .replace("[IdentityCode]", currentIdentity.identityCode);
                window.open(webAddr + url);
            })
        } else if (data.pcLinkType === '2') {
            // window.getWebAddr(data.sysId, function (webAddr) {
            //     let url = data.pcLink
            //     commonOpenClient(url, { WebSvrAddr: webAddr })
            // })
            message.info(`${data.msgSourceName}为客户端应用，请前往桌面打开`)
        } else if (data.pcLinkType === '3') {
            window.open(data.pcLinkType.replace("[token]", sessionStorage.getItem("token")).replace("[IdentityCode]", currentIdentity.identityCode), '_blank')
        } else if (data.pcLinkType === '4') {
            if (data.templateId === '20003' || data.templateId === '20001') {
                handleScheduleMsg(data)
            }
        }

        if (data.status == 0) {
            axiosMethod({
                type: 'PUT',
                url: `/api/system/manage/update/status`,
                body: {
                    userId: userInfo.UserID,
                    schoolId: userInfo.SchoolID,
                    sysMsgId: data.sysMsgId,
                },
                isNoTimeout: true,
                callback: function (res) {
                    setSelectList([])
                    getList()
                    window.remindSocket && window.remindSocket.send(JSON.stringify({
                        messageType: 2,
                        clientType: 4,
                        userId: userInfo.UserID,
                        encryptionCode: md5(userInfo.UserID).split('').reverse().join(''),
                        param: {
                            userId: userInfo.UserID,
                            userType: userInfo.UserType,
                            schoolId: userInfo.SchoolID
                        }
                    }))
                    window.getReadInfo && typeof window.getReadInfo === 'function' && window.getReadInfo()
                }
            })
        } else {
            setSelectList([])
            getList()
        }
        //点击消息跳转

    }, [currentIdentity, userInfo, getList]);

    const selectNotice = useCallback((data, index, e) => {  //选择单个消息
        e.stopPropagation();
        console.log(data, index, e.target.value)
        let list = JSON.parse(JSON.stringify(selectList)), target = "";
        list.forEach((item, index) => {
            if (item.sysMsgReceiverId === data.sysMsgReceiverId) {
                target = index;
            }
        })
        if (typeof target === "number") {
            list.splice(target, 1);
        } else {
            list.push(data);
        }

        let messageArr = JSON.parse(JSON.stringify(messageInfo))
        messageArr.forEach(item => {
            if (item.sysMsgReceiverId == data.sysMsgReceiverId) {
                item.check = !item.check
            }
        })
        setMessageInfo(messageArr)
        console.log(list)
        setSelectList(list);
    }, [selectList, messageInfo]);

    const changeSelectSign = useCallback((e) => {  //全选
        let list = [];
        if (e.target.checked) {
            list = Array.isArray(messageInfo) ? messageInfo : [];
            messageInfo.forEach(item => {
                item.check = true
            })
        } else {
            messageInfo.forEach(item => {
                item.check = false
            })
            list = []
        }
        setSelectList(list);
    }, [messageInfo]);

    const setNoreceive = useCallback((data, type, e) => {  //设置屏蔽/取消屏蔽
        e && e.stopPropagation();
        let isPushList = []
        if (type == 1) {
            isPushList.push({
                templateId: data.templateId,
                isPush: 0
            })
        } else {
            if (selectList.length < 1) {
                message.warn('至少选择一条消息')
                return
            }
            selectList.forEach(item => {
                if (item.isClosable == 1) {
                    isPushList.push({
                        templateId: item.templateId,
                        isPush: 0
                    })
                }
            })
        }

        if (isPushList.length <= 0) {
            setSelectList([])
            getList()
            message.warn('当前无可进行屏蔽操作的消息')
            return
        }

        dispatch({
            type: "SET_ALERTINFO",
            data: {
                visible: true,
                title: type == 1 ? "确定要屏蔽该消息吗？" : "确定要屏蔽所选消息吗？",
                smallTitle: '屏蔽后可在消息设置里恢复',
                onCancel: function () {
                    dispatch({
                        type: "SET_ALERTINFO",
                        data: {}
                    })
                },
                onOk: function () {
                    axiosMethod({
                        type: "put",
                        url: "/api/setting/manage/batch/shield",
                        body: {
                            schoolId: userInfo.SchoolID,
                            userId: userInfo.UserID,
                            isPushList,
                            // load: true
                        },
                        callback: function (res) {
                            let sysMsgReceiverIds = []
                            sysMsgReceiverIds.push(data.sysMsgReceiverId)
                            message.success("设置成功");
                            setSelectList([])
                            setCurrentIndex(currentIndex-1)
                        }
                    });
                }
            }
        })

    }, [selectList, userInfo]);

    const setDelete = useCallback((data, type, e) => {   //设置删除
        e && e.stopPropagation();
        let selectArr = []

        if (data) {
            selectArr.push(data.sysMsgReceiverId)
        }
        selectList.forEach(i => {
            selectArr.push(i.sysMsgReceiverId)
        })

        if (selectArr.length === 0 && type != -2) {
            message.warn('请至少选择一条消息')
            return
        }

        dispatch({
            type: "SET_ALERTINFO",
            data: {
                visible: true,
                title: type === -1 ? "确定要删除该消息吗？" : "确定要清空全部的系统提醒消息吗？",
                smallTitle: '删除后将无法恢复',
                onCancel: function () {
                    dispatch({
                        type: "SET_ALERTINFO",
                        data: {}
                    })
                },
                onOk: function () {
                    let url = '', body = {}
                    if (type == -1) {
                        url = '/api/system/manage/batch/delete'
                        body = {
                            schoolId: userInfo.SchoolID,
                            userId: userInfo.UserID,
                            sysMsgReceiverIds: selectArr.length > 0 ? selectArr : [data.sysMsgReceiverId]
                        }
                    } else {
                        dispatch({
                            type: "SET_ALERTINFO",
                            data: {}
                        })
                        setLoadVisible(true)
                        url = '/api/system/manage/delete/all'
                        body = {
                            schoolId: userInfo.SchoolID,
                            userId: userInfo.UserID,
                        }
                    }
                    axiosMethod({
                        type: "delete",
                        url,
                        body,
                        isNoTimeout: true,
                        callback: function (res) {
                            if (type == -1) {
                                message.success("删除成功");
                            } else {
                                setLoadVisible(false)
                                message.success("清空成功");
                            }
                            dispatch({
                                type: "SET_ALERTINFO",
                                data: {}
                            })

                            setSelectList([]);
                            setCurrentIndex(currentIndex-1)
                            window.getReadInfo()
                        }
                    });
                }
            }
        })

    }, [userInfo, dispatch, getList, selectList, messageApi]);


    const changePush = useCallback((data, value, type) => {  //消息设置，type:one || group 
        console.log(data, value, type)
        if (type === "one") {
            axiosMethod({
                type: "put",
                url: "/api/setting/manage/batch/shield",
                body: {
                    schoolId: userInfo.SchoolID,
                    userId: userInfo.UserID,
                    isPushList: [{
                        templateId: data.templateId,
                        isPush: value ? 1 : 0,
                    }],
                },
                callback: function (res) {
                    message.success("设置成功");
                    let info = JSON.parse(JSON.stringify(settingInfo));
                    info.forEach((item) => {
                        item.templateList.forEach((child) => {
                            if (child.templateId === data.templateId) {
                                child.isPush = value ? 0 : 1;
                            }
                        })
                        let flag = item.templateList.some(child => {
                            return child.isPush == 0
                        })

                        item.check = flag
                        console.log('flag', flag)
                    })
                    setSettingInfo(info);
                    getList()
                }
            });
        } else {
            let list = [];
            Array.isArray(data.templateList) &&
                data.templateList.forEach((child) => {
                    list.push({
                        templateId: child.templateId,
                        isPush: value ? 1 : 0
                    });

                })
            axiosMethod({
                type: "put",
                url: "/api/setting/manage/batch/shield",
                body: {
                    schoolId: userInfo.SchoolID,
                    userId: userInfo.UserID,
                    isPushList: list
                },
                callback: function (res) {
                    message.success("设置成功");
                    let info = JSON.parse(JSON.stringify(settingInfo));
                    info.forEach((item) => {
                        if (item.msgTypeId === data.msgTypeId) {
                            item.check = value
                            item.templateList.forEach((child) => {
                                child.isPush = value ? 0 : 1;
                            })
                        }
                    })
                    getList()
                    setSettingInfo(info);
                    // getSettingInfo();
                }
            });
        }
    }, [userInfo, settingInfo, getList]);

    useEffect(() => {
        setSelectList([]);
        getList();
    }, [getList, currentIndex]);
    return (
        <div className='main_message'>
            {contextHolder}
            <Spin spinning={loadVisible} tip="加载中...">
                <div className="notice_option">
                    <span className="list_info">共<span>{listTotal || 0}</span>条</span>
                    <span className="setting_btn" onClick={getSettingInfo}><i></i>消息设置</span>
                    <span className="delete_btn" onClick={() => setDelete("", -2)}><i></i>清空全部</span>
                    <Search className="option_search" searchMethod={searchMethod} placeholder="搜索消息内容..." />

                </div>
                <div className="notice_list">
                    {
                        Array.isArray(messageInfo) &&
                            messageInfo.length > 0 ?
                            messageInfo.map((item, index) => (
                                <div
                                    className="notice_one"
                                    key={index}
                                    style={{ cursor: (!item.pcLink &&  item.templateId!=='20001' && item.templateId!=='20003' ? "default" : "") }}
                                    onClick={() => noticeClick(item)}>
                                    <Checkbox
                                        className="checklogo"
                                        checked={item.check}
                                        onClick={(e) => selectNotice(item, index, e)}
                                    />
                                    <div className="one_info">
                                        <h4 className="info_title"
                                            style={{ color: `${item.status == 0 ? '' : '#9999'}` }}
                                            title={item.msgPushContent}
                                        >
                                            {item.msgPushContent}
                                        </h4>
                                        <p className="info_detail">
                                            <span style={{ color: "#ff6600", fontSize: '12px' }}>{item.msgSourceName}</span>
                                            <span className="detail_line"></span>
                                            {item.msgPushTime && item.msgPushTime.substr(0, 16)}
                                        </p>
                                    </div>
                                    <div className="one_option">
                                        {
                                            item.isClosable === '1' ?
                                                <>
                                                    <span className="blue_text" onClick={(e) => setNoreceive(item, 1, e)}>屏蔽此类消息</span>
                                                    <span className="slice_line"></span>
                                                </> :
                                                ""
                                        }
                                        <span className="red_text" onClick={(e) => setDelete(item, -1, e)}>删除</span>
                                    </div>
                                </div>
                            )) :
                            <Empty text={'暂无系统提醒'} style={{ marginTop: 160 }} />
                    }
                </div>
                {
                    messageInfo.length > 0 ?
                        <div className="notice_footer">
                            <div className="option_all" style={{ display: `${listTotal > 0 ? 'block' : 'none'}` }}>
                                <Checkbox
                                    checked={selectStatus === 2 ? true : false}
                                    onChange={changeSelectSign}
                                    indeterminate={selectStatus === 1 ? true : false}><span style={{position: 'relative', top: '-2px'}}>全选</span></Checkbox>
                                <span style={{position: 'relative', top: '-3.5px'}} className="red_btn" onClick={(e) => setDelete("", -1, e)}>批量删除</span>
                                <span style={{position: 'relative', top: '-3.5px'}} className="red_btn" onClick={(e) => setNoreceive("", e)}>批量屏蔽</span>
                            </div>
                            <div className="lg-skin-s2" style={{ display: `${listTotal > 9 ? 'block' : 'none'}` }}>
                                <LgPaginationA
                                    total={Math.ceil(listTotal / 9)}
                                    size="normal"
                                    currentPage={currentIndex}
                                    onChangePage={(pageIndex) => {
                                        setCurrentIndex(pageIndex);
                                    }}
                                ></LgPaginationA>
                            </div>
                        </div> : ''
                }
            </Spin>
            <Modal
                width={720}
                height={489}
                className={sessionStorage.getItem('skin') == '1' ? 'setting_modal setting_modal1' : sessionStorage.getItem('skin') == '2' ? 'setting_modal setting_modal2' : 
                    sessionStorage.getItem('skin') == '3' ? 'setting_modal setting_modal3' : sessionStorage.getItem('skin') == '4' ? 'setting_modal setting_modal4' :
                    sessionStorage.getItem('skin') == '5' ? 'setting_modal setting_modal5' : sessionStorage.getItem('skin') == '6' ? 'setting_modal setting_modal6' : 'setting_modal'
                }
                visible={settingVisible}
                changeVisible={setSettingVisible}
                noFooter={true}
                title="系统提醒消息接收设置">
                <Scrollbars autoHeight autoHeightMax={460}>
                    {
                        settingInfo && settingInfo.length > 0 ?
                            settingInfo.map((item, index) => (
                                <div className="setting_group" key={index}>
                                    <h4 className="group_title">
                                        {item.msgTypeDescription}
                                        <Switch className="setting_switch" checked={item.check} defaultChecked={item.check} onChange={(value) =>
                                            changePush(item, value, "group")} />
                                    </h4>
                                    <ul className="group_list">
                                        {
                                            Array.isArray(item.templateList) &&
                                            item.templateList.map((child, index2) => (
                                                <li key={index2}>
                                                    <span className="one_name" title={child.templateDescription}>{child.templateDescription}</span>
                                                    <Switch className="setting_switch" checked={Number(child.isPush) == 1 ? false : true} onChange={(value) => changePush(child, value, "one")} />
                                                </li>
                                            ))
                                        }
                                    </ul>
                                </div>
                            )) :
                            <Empty style={{ marginTop: 140 }} text="暂无消息设置信息~" />
                    }
                </Scrollbars>
            </Modal>
        </div>
    )
}
export default Todo;